using System;
using System.Diagnostics;

namespace OwnList
{
	public class OwnList<T>
	{
		private static readonly int InitialCapacity = 4;
		
		private T[] storage;
		private int currentItemNumber;
		
		public int Count {
			get {
				return currentItemNumber;
			}
		}
		
		public OwnList ()
		{
			storage = new T[InitialCapacity];
			currentItemNumber = 0;
		}
		
		public void Add(T objectToAdd ) {
			storage[currentItemNumber] = objectToAdd;
			currentItemNumber++;
			if( NeedIncreaseCapacity() ) {
				IncreaseCapacity();
			}
		}
		
		public T Get(int index) 
		{
			if( index < 0 || index > storage.Length - 1 ) {
				throw new IndexOutOfRangeException("index out of range");	
			}
			return storage[index];
		}
		
		public T Remove() 
		{
			Debug.Assert( currentItemNumber >= 0 );
			Debug.Assert( currentItemNumber <= storage.Length );
			
			if( currentItemNumber == 0 ) 
			{
				throw new InvalidOperationException("Can't remove from empty list");
			}
			
			T item = storage[currentItemNumber - 1];
			storage[currentItemNumber - 1] = default(T);
			currentItemNumber--;
			return item;
		}
		
		private bool NeedIncreaseCapacity() 
		{
			Debug.Assert( currentItemNumber <= storage.Length );
			if( currentItemNumber == storage.Length ) {
				return true;
			}
			return false;
		}
		
		private void IncreaseCapacity() 
		{
		
			T[] newStorage = new T[storage.Length * 2];
			Array.Copy(storage, newStorage, storage.Length);
			storage = newStorage;
		}
		
	}
}

